// pages/product/newAddress/newAddress.js
const app = getApp(),
    globalData = app.globalData,
    api = require('../../../api/index'),
    utils = require('../../../utils/util');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isIpx: globalData.isIpx,
        region: [],
        consigneeName: '',
        consigneePhone: '',
        consigneeAddress: '',
        consigneeProvinceCity: '',
        consigneeStreet: '',
        id: '',
        isIpx: globalData.isIpx,
        isAdd: false,
        imageBaseUri: globalData.imageBaseUri,
        modalDel: {
            show: false,
            title: "温馨提示",
            content: "删除地址后不可恢复,请谨慎操作",
            confirmText: "确认删除",
        },
        toast: {
            visible: false,
            text: ''
        },
        showAddress: false, //是否展示地区
        submitUsable: true,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let isNew = options.isNew || false, // 是否新增地址
            item = options.item ? JSON.parse(options.item) : {}; // 编辑地址信息

        this.setData({
            isNew,
            item
        })

        if (isNew) {
            wx.setNavigationBarTitle({ title: '新增地址' })
        } else {
            wx.setNavigationBarTitle({ title: '编辑地址' })
        }

        console.log(item, 'address item')

        if (item.ConsigneeProvinceCity) {
            this.setData({
                showAddress: true,
                consigneeName: item.ConsigneeName,
                consigneePhone: item.ConsigneePhone,
                consigneeProvinceCity: item.ConsigneeProvinceCity,
                consigneeAddress: item.ConsigneeAddress,
                consigneeStreet: item.ConsigneeStreet,
                region: item.ConsigneeProvinceCity.split(',')
            })
        } else {
            this.setData({
                showAddress: false,
                consigneeName: '',
                consigneePhone: '',
                consigneeProvinceCity: '',
                consigneeAddress: '',
                consigneeStreet: '',
                region: []
            })
        }

    },

    /**
     * 选择地址
     */
    bindRegionChange(e) {
        this.setData({
            region: e.detail.value,
            consigneeProvinceCity: e.detail.value,
            showAddress: true
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 重新加载
     */
    reload() {
        this.setData({ status: 0 });
        // this.data.id && this.getAddressById();
    },

    /**
     * 地址详情
     */
    // async getAddressById() {
    //     try {
    //         let res = await api.address.getAddressById(this.data.id);
    //         let data = res.data.data || {};
    //         let region = data.consigneeProvinceCity ? data.consigneeProvinceCity.split(',') : '';

    //         this.setData({
    //             consigneeName: data.consigneeName || '',
    //             consigneePhone: data.consigneePhone || '',
    //             consigneeAddress: data.consigneeAddress || '',
    //             consigneeProvinceCity: data.consigneeProvinceCity,
    //             consigneeStreet: data.consigneeStreet,
    //             region,
    //             status: 2,
    //             isAdd: false,
    //         })
    //     } catch (e) {
    //         utils.log.error('主流程发生错误', e);
    //         this.setData({ status: 1 });
    //     }
    // },

    /**
     * 提交
     */
    async submit() {
        //提交中
        if (!this.data.submitUsable) return false;

        let text = '';

        if (!this.data.consigneeName)
            text = '请填写收货人的姓名';
        else if (!globalData.exp.phone.test(this.data.consigneePhone))
            text = '请填写正确的手机号';
        else if (!this.data.consigneeProvinceCity)
            text = '请选择省市区';
        else if (!this.data.consigneeStreet)
            text = '请填写详细地址';

        //验证未通过
        if (text) {
            return this.setData({
                'toast.visible': true,
                'toast.text': text,
            });
        }

        let obj = {
            id: "",
            provinceId: "",
            cityId: "",
            areaId: "",
            isDefault: true,
            address: "",
            phoneNumber: "",
            zip: "",
            consigneeName: this.data.consigneeName,
            consigneePhone: this.data.consigneePhone,
            consigneeStreet: this.data.consigneeStreet,
            consigneeProvinceCity: this.data.consigneeProvinceCity.toString(),
            consigneeAddress: this.data.consigneeProvinceCity.toString().replace(/,/g, "") + this.data.consigneeStreet
        };

        !this.data.isAdd && (obj.id = this.data.id);

        //提交防抖
        this.setData({ submitUsable: false });
        wx.showLoading({ title: '提交中，请稍后...' });

        if (this.data.isNew) {
            try {
                await api.address.newAddress(obj);

                let pages = getCurrentPages(),
                    p1 = utils.getRouteStackUri('/pages/mall/confimorder/chooseAddre/chooseAddre'),
                    p2 = utils.getRouteStackUri('/pages/mall/confimorder/confimorder/confimorder');

                pages[p1] && pages[p1].pageDirty();
                //修改地址时，确认订单页需刷新，添加地址时则不需要
                pages[p2] && pages[p2].pageDirty();

                wx.navigateBack();
            } catch (e) {
                utils.log.error('新增收货地址失败', e);
                this.setData({
                    status: 1,
                    toast: {
                        visible: true,
                        text: e.data.ErrMsg
                    }
                });
            } finally {
                wx.hideLoading();
            }
        } else {
            obj.id = this.data.item.Id;
            try {
                await api.address.editAddress(obj);

                let pages = getCurrentPages(),
                    p1 = utils.getRouteStackUri('/pages/mall/confimorder/chooseAddre/chooseAddre'),
                    p2 = utils.getRouteStackUri('/pages/mall/confimorder/confimorder/confimorder');

                pages[p1] && pages[p1].pageDirty();
                //修改地址时，确认订单页需刷新，添加地址时则不需要
                pages[p2] && pages[p2].pageDirty();

                wx.navigateBack();
            } catch (e) {
                utils.log.error('编辑收货地址失败', e);
                this.setData({
                    status: 1,
                    toast: {
                        visible: true,
                        text: e.data.ErrMsg
                    }
                });
            } finally {
                wx.hideLoading();
            }
        }


    },

    /**
     * 收货人姓名
     */
    inputName(e) {
        this.setData({
            consigneeName: e.detail.value
        });
    },

    /**
     * 收货人手机号
     */
    consigneePhone(e) {
        this.setData({
            consigneePhone: e.detail.value
        });
    },

    /**
     * 收获详细地址
     */
    consigneeStreet(e) {
        this.setData({
            consigneeStreet: e.detail.value
        });
    },

    /**
     * 收货地址（省市区）
     */
    consigneeProvinceCity(e) {
        this.setData({
            consigneeProvinceCity: e.detail.value
        });
    },
})